/**
 * Copyright 2010 Jake Jackson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jake.nb.ext.ant.hints;

import java.util.Collection;
import java.util.LinkedHashSet;
import javax.swing.text.Document;
import org.netbeans.modules.editor.NbEditorUtilities;
import org.netbeans.spi.editor.errorstripe.UpToDateStatus;
import org.netbeans.spi.editor.errorstripe.UpToDateStatusProvider;
import org.netbeans.spi.editor.hints.ErrorDescription;
import org.netbeans.spi.editor.hints.HintsController;
import org.openide.filesystems.FileChangeAdapter;
import org.openide.filesystems.FileChangeListener;
import org.openide.filesystems.FileEvent;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Lookup;
import org.openide.util.RequestProcessor;
import org.openide.util.lookup.Lookups;

class AntStatusProvider extends UpToDateStatusProvider {

  private Document document;
  private FileChangeListener listener;

  AntStatusProvider(Document doc) {
    this.document = doc;
    listener = new FileChangeAdapter() {

      @Override
      public void fileChanged(FileEvent fe) {
        RequestProcessor.getDefault().post(new Runnable() {

          @Override
          public void run() {
            checkHints();
          }
        });
      }
    };

    FileObject fo = NbEditorUtilities.getFileObject(document);
    fo.addFileChangeListener(FileUtil.weakFileChangeListener(listener, fo));
    RequestProcessor.getDefault().post(new Runnable() {

      @Override
      public void run() {
        checkHints();
      }
    });
  }

  void checkHints() {
    final Lookup lookup = Lookups.forPath("org-jake-nb-ext-ant-hints"); // NOI18N
    final Collection<? extends AntHint> lookupAll = lookup.lookupAll(AntHint.class);
    final Collection<ErrorDescription> allErrors = new LinkedHashSet<ErrorDescription>();
    final SpanContainer spanContainer = new SpanContainer(document);
    for (final AntHint antHint : lookupAll) {
      if(antHint.getConfiguration().isEnabled()) {
        final Collection<ErrorDescription> errors = antHint.getErrors(spanContainer);
        if(errors != null) {
          allErrors.addAll(errors);
        }
      }
    }
    HintsController.setErrors(document, "ant", allErrors); // NOI18N
  }

  @Override
  public UpToDateStatus getUpToDate() {
    return UpToDateStatus.UP_TO_DATE_OK;
  }
}
